package handler

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"zg3/live/api/request"
	"zg3/live/internal/dao"
	"zg3/live/internal/model"
	"zg3/live/pkg"
)

func UserRegister(c *gin.Context) {
	var req request.UserRegisterReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "参数验证失败",
			"data": err.Error(),
		})
		return
	}
	user := dao.FindUserName(req.Username)
	if user.Id != 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "该用户名已存在",
			"data": nil,
		})
		return
	}
	user = model.User{
		Username: req.Username,
		Password: req.Password,
	}
	if !dao.Create(&user) {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "注册失败",
			"data": false,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "注册成功",
		"data": user,
	})
	return
}

func UserLogin(c *gin.Context) {
	var req request.UserLoginReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "参数验证失败",
			"data": err.Error(),
		})
		return
	}
	user := dao.FindUserName(req.Username)
	if user.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "该用户不存在",
			"data": nil,
		})
		return
	}
	if user.Password != req.Password {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "密码错误",
			"data": nil,
		})
		return
	}
	token, _ := pkg.NewJWT("2210a").CreateToken(pkg.CustomClaims{
		ID: user.Id,
	})
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": token,
	})
	return
}
